package com.jwm.power.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.jwm.power.model.common.EnumMenu;
import com.jwm.power.model.common.EnumOperate;
import com.jwm.power.model.common.EnumResult;
import com.jwm.power.model.entity.Logs;
import com.jwm.power.model.entity.Menus;
import com.jwm.power.model.entity.Users;
import com.jwm.power.model.reponse.ResponseData;
import com.jwm.power.repository.LogsRepository;
import com.jwm.power.repository.MenusRepository;
import com.jwm.power.service.MenusService;
import com.jwm.power.util.Ut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.ServletRequestDataBinder;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
@Transactional
public class MenusServiceImpl implements MenusService {
    @Autowired
    private MenusRepository menusRepository;
    @Autowired
    private LogsRepository logsRepository;

    //  设置菜单
    @Override
    public ResponseData SaveMenus(HttpServletRequest request) {
        try {
            Users users = (Users) StpUtil.getSession().get("users");
            Menus model_New = new Menus();
            ServletRequestDataBinder binder =
                    new ServletRequestDataBinder(model_New);
            binder.bind(request);
            if (model_New.getParentcode() == null || model_New.getParentcode().equals("")) {
                model_New.setParentcode("00");
            }
            Integer operationType = 0;
            if (model_New.getMenuid() != null && model_New.getMenuid() > 0) {
                operationType = 1;
            } else {
                String maxCode = menusRepository.getMaxCode(model_New.getParentcode());
                maxCode = maxCode != null ? maxCode : "0";
                String parentCode = model_New.getParentcode().equals("00") ? "" : model_New.getParentcode();
                model_New.setMenucode(parentCode + String.format("%02d", Integer.parseInt(maxCode) + 1));
//                String maxSn = menusRepository.getMaxSn(model_New.getParentcode());
//                maxSn = maxSn != null ? maxSn : "0";
//                model_New.setOrderbyid(parentCode + String.format("%02d", Integer.parseInt(maxCode) + 1));
            }

            menusRepository.save(model_New);

            //  添加日志
            Logs log = Ut.SaveLog("menus", model_New.getMenuname(), operationType == 1 ? EnumOperate.EDIT : EnumOperate.ADD, users);
            logsRepository.save(log);
            return new ResponseData(EnumResult.SUCCESS, model_New);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }

}
